package com.uinnova.product.eam.workable.listener;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component("reSubmitToRejectMuilityUserListener")
public class ReSubmitToRejectMuilityUserListener implements ExecutionListener {

    @Autowired
    private transient HistoryService historyService;

    @Override
    public void notify(DelegateExecution execution) {
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .orderByHistoricTaskInstanceEndTime().asc().list()
                .stream().filter(hTask -> !"MI_END".equals(hTask.getDeleteReason())).collect(Collectors.toList());
        //过滤掉自动关闭任务
        HistoricTaskInstance historicTaskInstance = list.get(list.size() - 1);

        List<HistoricVariableInstance> historicVariableInstanceList =  historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .taskId(historicTaskInstance.getId()).list();
        //获取上一个节点执行结果
        Map<String, Object> lastVariables = historicVariableInstanceList.stream()
                .filter(v -> !StringUtils.isEmpty(v.getVariableName()))
                .filter(v -> v.getValue() != null)
                .collect(Collectors.toMap(HistoricVariableInstance::getVariableName, HistoricVariableInstance::getValue));

        String assignee = historicTaskInstance.getAssignee();
        Map<String, Object> variables = execution.getVariables();
        variables.put("assigneeList", Arrays.asList(assignee));
        //判断是否是撤回 此监听器只有在驳回再提交或者撤回再提交的时候执行
        if (!lastVariables.get("pass").equals("recall")) {
            execution.setVariables(variables);
        }
    }
}
